﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace DusonFramework.Core
{
    public class StringHelper
    {
        /// <summary>
        /// 截取字符串函数
        /// </summary>
        public static string GetSubString(string Str, int Num)
        {
            string sdot = string.Empty;
            if (Str == null || Str == "")
                return string.Empty;
            string outstr = string.Empty;
            int n = 0;
            foreach (char ch in Str)
            {
                n += System.Text.Encoding.Default.GetByteCount(ch.ToString());
                if (n > Num)
                {
                    sdot = "..";
                    break;
                }
                else
                {
                    outstr += ch;
                }
            }
            if (Str.Length > 2)
            {
                return outstr + sdot;
            }
            else
            {
                return outstr;
            }
        }
        /// <summary>
        /// 截取字符串函数
        /// </summary>
        /// <param name="Str">所要截取的字符串</param>
        /// <param name="Num">截取字符串的长度</param>
        /// <param name="Len">返回实际长度</param>
        /// <returns></returns>
        public static string GetSubString(string Str, int Num, out int Len)
        {
            Len = 0;
            if (string.IsNullOrEmpty(Str))
                return "";
            string outstr = string.Empty;

            foreach (char ch in Str)
            {
                Len += System.Text.Encoding.Default.GetByteCount(ch.ToString());
                if (Len > Num)
                    break;
                else
                    outstr += ch;
            }
            return outstr;
        }

        /// <summary>
        /// 截取字符串函数
        /// </summary>
        /// <param name="Str">所要截取的字符串</param>
        /// <param name="Num">截取字符串的长度</param>
        /// <param name="Num">截取字符串后省略部分的字符串</param>
        /// <returns></returns>
        public static string GetSubString(string Str, int Num, string LastStr)
        {
            return (Str.Length > Num) ? Str.Substring(0, Num) + LastStr : Str;
        }

        /// <summary>
        /// 过滤字符
        /// </summary>
        public static string Filter(string sInput)
        {
            if (sInput == null || sInput.Trim() == string.Empty)
                return null;
            string sInput1 = sInput.ToLower();
            string output = sInput;
            string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";
            if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)
            {
                throw new Exception("字符串中含有非法字符!");
            }
            else
            {
                output = output.Replace("'", "''");
            }
            return output;
        }

        #region 全角半角转换

        /// <summary>
        /// 转全角的函数(SBC case)
        /// </summary>
        /// <param name="input">任意字符串</param>
        /// <returns>全角字符串</returns>
        ///<remarks>
        ///全角空格为12288，半角空格为32
        ///其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
        ///</remarks>
        public static string ToSBC(string input)
        {
            //半角转全角：
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char)12288;
                    continue;
                }
                if (c[i] < 127)
                    c[i] = (char)(c[i] + 65248);
            }
            return new string(c);
        }

        /// <summary> 转半角的函数(DBC case) </summary>
        /// <param name="input">任意字符串</param>
        /// <returns>半角字符串</returns>
        ///<remarks>
        ///全角空格为12288，半角空格为32
        ///其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
        ///</remarks>
        public static string ToDBC(string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new string(c);
        }

        #endregion

        /// <summary>   
        ///  获得某个字符串在另个字符串中出现的次数   
        /// </summary>   
        /// <param name="strOriginal">要处理的字符</param>   
        /// <param name="strSymbol">符号</param>   
        /// <returns>返回值</returns>   
        public static int GetStrCount(string strOriginal, string strSymbol)
        {
            int count = 0;
            for (int i = 0; i < (strOriginal.Length - strSymbol.Length + 1); i++)
            {
                if (strOriginal.Substring(i, strSymbol.Length) == strSymbol)
                {
                    count = count + 1;
                }
            }
            return count;
        }

        /// <summary>   
        /// 获得某个字符串在另个字符串第一次出现时前面所有字符   
        /// </summary>   
        /// <param name="strOriginal">要处理的字符</param>   
        /// <param name="strSymbol">符号</param>   
        /// <returns>返回值</returns>   
        public static string GetFirstStr(string strOriginal, string strSymbol)
        {
            int strPlace = strOriginal.IndexOf(strSymbol);
            if (strPlace != -1)
                strOriginal = strOriginal.Substring(0, strPlace);
            return strOriginal;
        }

        /// <summary>   
        /// 获得某个字符串在另个字符串最后一次出现时后面所有字符   
        /// </summary>   
        /// <param name="strOriginal">要处理的字符</param>   
        /// <param name="strSymbol">符号</param>   
        /// <returns>返回值</returns>   
        public static string GetLastStr(string strOriginal, string strSymbol)
        {
            int strPlace = strOriginal.LastIndexOf(strSymbol) + strSymbol.Length;
            strOriginal = strOriginal.Substring(strPlace);
            return strOriginal;
        }

        /// <summary>   
        /// 获得两个字符之间第一次出现时前面所有字符   
        /// </summary>   
        /// <param name="strOriginal">要处理的字符</param>   
        /// <param name="strFirst">最前哪个字符</param>   
        /// <param name="strLast">最后哪个字符</param>   
        /// <returns>返回值</returns>   
        public static string GetTwoMiddleFirstStr(string strOriginal, string strFirst, string strLast)
        {
            strOriginal = GetFirstStr(strOriginal, strLast);
            strOriginal = GetLastStr(strOriginal, strFirst);
            return strOriginal;
        }

        /// <summary>   
        ///  获得两个字符之间最后一次出现时的所有字符   
        /// </summary>   
        /// <param name="strOriginal">要处理的字符</param>   
        /// <param name="strFirst">最前哪个字符</param>   
        /// <param name="strLast">最后哪个字符</param>   
        /// <returns>返回值</returns>   
        public static string GetTwoMiddleLastStr(string strOriginal, string strFirst, string strLast)
        {
            strOriginal = GetLastStr(strOriginal, strFirst);
            strOriginal = GetFirstStr(strOriginal, strLast);
            return strOriginal;
        }

        /// <summary>   
        /// 从数据库表读记录时,能正常显示   
        /// </summary>   
        /// <param name="strContent">要处理的字符</param>   
        /// <returns>返回正常值</returns>   
        public static string GetHtmlFormat(string strContent)
        {
            strContent = strContent.Trim();

            if (strContent == null)
            {
                return "";
            }
            strContent = strContent.Replace("<", "<");
            strContent = strContent.Replace(">", ">");
            strContent = strContent.Replace("\n", "<br />");
            return (strContent);
        }

        /// <summary>   
        /// 检查相等之后，获得字符串   
        /// </summary>   
        /// <param name="str">字符串1</param>   
        /// <param name="checkStr">字符串2</param>   
        /// <param name="reStr">相等之后要返回的字符串</param>   
        /// <returns>返回字符串</returns>   
        public static string GetCheckStr(string str, string checkStr, string reStr)
        {
            if (str == checkStr)
            {
                return reStr;
            }
            return "";
        }

        /// <summary>   
        /// 检查相等之后，获得字符串   
        /// </summary>   
        /// <param name="str">数值1</param>   
        /// <param name="checkStr">数值2</param>   
        /// <param name="reStr">相等之后要返回的字符串</param>   
        /// <returns>返回字符串</returns>   
        public static string GetCheckStr(int str, int checkStr, string reStr)
        {
            if (str == checkStr)
            {
                return reStr;
            }
            return "";
        }
        /// <summary>   
        /// 检查相等之后，获得字符串   
        /// </summary>   
        /// <param name="str"></param>   
        /// <param name="checkStr"></param>   
        /// <param name="reStr"></param>   
        /// <returns></returns>   
        public static string GetCheckStr(bool str, bool checkStr, string reStr)
        {
            if (str == checkStr)
            {
                return reStr;
            }
            return "";
        }
        /// <summary>   
        /// 检查相等之后，获得字符串   
        /// </summary>   
        /// <param name="str"></param>   
        /// <param name="checkStr"></param>   
        /// <param name="reStr"></param>   
        /// <returns></returns>   
        public static string GetCheckStr(object str, object checkStr, string reStr)
        {
            if (str == checkStr)
            {
                return reStr;
            }
            return "";
        }
        /// <summary>   
        /// 截取左边规定字数字符串,超过字数用endStr结束   
        /// </summary>   
        /// <param name="str">需截取字符串</param>   
        /// <param name="length">截取字数</param>   
        /// <param name="endStr">超过字数，结束字符串，如"..."</param>   
        /// <returns>返回截取字符串</returns>   
        public static string GetLeftStr(string str, int length, string endStr)
        {
            string reStr;
            if (length < GetStrLength(str))
            {
                reStr = str.Substring(0, length) + endStr;
            }
            else
            {
                reStr = str;
            }
            return reStr;
        }

        /// <summary>   
        /// 截取左边规定字数字符串,超过字数用...结束   
        /// </summary>   
        /// <param name="str">需截取字符串</param>   
        /// <param name="length">截取字数</param>   
        /// <returns>返回截取字符串</returns>   
        public static string GetLeftStr(string str, int length)
        {
            string reStr;
            if (length < str.Length)
            {
                reStr = str.Substring(0, length) + "...";
            }
            else
            {
                reStr = str;
            }
            return reStr;
        }

        /// <summary>   
        /// 截取左边规定字数字符串,超过字数用...结束   
        /// </summary>   
        /// <param name="str">需截取字符串</param>   
        /// <param name="length">截取字数</param>   
        /// <param name="subcount">若超过字数右边减少的字符长度</param>   
        /// <returns>返回截取字符串</returns>   
        public static string GetLeftStr(string str, int length, int subcount)
        {
            string reStr;
            if (length < str.Length)
            {
                reStr = str.Substring(0, length - subcount) + "...";
            }
            else
            {
                reStr = str;
            }
            return reStr;
        }

        /// <summary>   
        /// 获得双字节字符串的字节数   
        /// </summary>   
        /// <param name="str">要检测的字符串</param>   
        /// <returns>返回字节数</returns>   
        public static int GetStrLength(string str)
        {
            ASCIIEncoding n = new ASCIIEncoding();
            byte[] b = n.GetBytes(str);
            int l = 0;  // l 为字符串之实际长度   
            for (int i = 0; i < b.Length; i++)
            {
                if (b[i] == 63)  //判断是否为汉字或全脚符号   
                {
                    l++;
                }
                l++;
            }
            return l;
        }

        /// <summary>   
        /// 移除字符串首尾某些字符   
        /// </summary>   
        /// <param name="strOriginal">要操作的字符串</param>   
        /// <param name="startStr">要在字符串首部移除的字符串</param>   
        /// <param name="endStr">要在字符串尾部移除的字符串</param>   
        /// <returns>string</returns>   
        public static string RemoveStartOrEndStr(string strOriginal, string startStr, string endStr)
        {
            char[] start = startStr.ToCharArray();
            char[] end = endStr.ToCharArray();
            return strOriginal.TrimStart(start).TrimEnd(end);
        }

        /// <summary>   
        /// 删除指定位置指定长度字符串   
        /// </summary>   
        /// <param name="strOriginal">要操作的字符串</param>   
        /// <param name="startIndex">开始删除字符的位置</param>   
        /// <param name="count">要删除的字符数</param>   
        /// <returns>string</returns>   
        public static string RemoveStr(string strOriginal, int startIndex, int count)
        {
            return strOriginal.Remove(startIndex, count);
        }

        /// <summary>   
        /// 从左边填充字符串   
        /// </summary>   
        /// <param name="strOriginal">要操作的字符串</param>   
        /// <param name="totalWidth">结果字符串中的字符数</param>   
        /// <param name="paddingChar">填充的字符</param>   
        /// <returns>string</returns>   
        public static string LeftPadStr(string strOriginal, int totalWidth, char paddingChar)
        {
            if (strOriginal.Length < totalWidth)
                return strOriginal.PadLeft(totalWidth, paddingChar);
            return strOriginal;
        }

        /// <summary>   
        /// 从右边填充字符串   
        /// </summary>   
        /// <param name="strOriginal">要操作的字符串</param>   
        /// <param name="totalWidth">结果字符串中的字符数</param>   
        /// <param name="paddingChar">填充的字符</param>   
        /// <returns>string</returns>   
        public static string RightPadStr(string strOriginal, int totalWidth, char paddingChar)
        {
            if (strOriginal.Length < totalWidth)
                return strOriginal.PadRight(totalWidth, paddingChar);
            return strOriginal;
        }

        ///<summary>
        /// 将字符串形式的IP转换位long
        ///</summary>
        ///<param name="ipAddress"></param>
        ///<returns></returns>
        public static long IpToLong(string ipAddress)
        {
            if (string.IsNullOrWhiteSpace(ipAddress)) return 0;

            byte[] ip_bytes = new byte[8];
            string[] strArr = ipAddress.Split(new char[] { '.' });
            if (strArr.Length != 4) return 0;

            for (int i = 0; i < 4; i++)
            {
                byte b = 0;
                if (byte.TryParse(strArr[3 - i], out b))
                {
                    ip_bytes[i] = b;
                }
                else
                {
                    return 0;
                }
            }
            return BitConverter.ToInt64(ip_bytes, 0);
        }
    }
}
